package com.shijie.newvideo.base;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout2;
import com.shijie.newvideo.ApiException;
import com.shijie.newvideo.BaseFragment;
import com.shijie.newvideo.EmptyRecyclerView;
import com.shijie.newvideo.EmptySupportedRecyclerView;
import com.shijie.newvideo.R;
import com.shijie.newvideo.SpUtil;
import com.shijie.newvideo.StringUtils;
import com.shijie.newvideo.header.HeaderAndFooterWrapperAdapter;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

import pl.droidsonroids.gif.GifImageView;

/**
 * @author zhangdunxiang
 * @date 2017/5/27.
 */

public abstract class BaseRefreshRecyclerViewFragment<T> extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {

    //    @BindView(R.id.swipeToLoadLayout)
    protected SwipeToLoadLayout2 swipeToLoadLayout;
    //    @BindView(R.id.recycler_view)
    protected EmptySupportedRecyclerView mRecyclerView;

    public Context mContext;
    protected List<T> mData;
    protected RecyclerView.Adapter adapter;

    /**
     * 是否显示到底了的提示
     */
    private boolean mShowBottomToast = true;

    /**
     * 滚动到底部的提示，在滚动到底部时提示并置为true，在向上滑动时置为false
     */
    private boolean mBottomToastLock;

    /**
     * 当前页数，加载下一页时是skip+1
     */
    protected int mPageNo = 1;

    /**
     * 第一页从几开始，可以配置，默认是从1开始，如果从0开始，可以在子类修改
     */
    protected int firstPageNo = 1;

    /**
     * 每页显示的条数
     */
    protected int mPageSize = 20;

    /**
     * 是否第一次进入
     */
    private boolean isFirst = true;
    /**
     * 是否是搜索页面
     */
    private boolean isSearch = false;
    private String cacheKey;


    protected RelativeLayout mLlEmpty;
    protected GifImageView mIvEmpty;
    protected TextView mTvEmpty;
    protected TextView tv_empty_click;
    protected TextView tvReloadError;
    protected ImageView mIvErrorEmpty;
    protected ImageView mIvSearchImage;
    private boolean isFirstFlag = false;
    //显示没有更多数据的ui
    public boolean isShowNoMoreLayout;//是否显示没有更多的布局
    public View loadNoDataView;
    public LinearLayout mLlNoMoreData;
    public TextView mTvNoMoreDataTip;
    public boolean showNoMoreData;
    public String showMoreTips;


    protected abstract RecyclerView.Adapter createAdapter(List<T> list);

    protected abstract void getListData(int pageNo);

    protected String getCacheKey() {
        return null;
    }

    ;

    /**
     * recycler view 的LayoutManage
     * 可以重写改方法设置不同的layoutManage
     *
     * @param context context
     * @return 默认为 {@linkplain LinearLayoutManager}
     */
    protected RecyclerView.LayoutManager createLayoutManager(Context context) {
        return new LinearLayoutManager(context);
    }


    @Override
    public View initView() {
        mview = setRefreshLayout();
        swipeToLoadLayout = (SwipeToLoadLayout2) mview.findViewById(R.id.swipeToLoadLayout);
        swipeToLoadLayout.setBackgroundResource(setRefreshBg());

        mRecyclerView = (EmptySupportedRecyclerView) mview.findViewById(R.id.recycler_view);
        //设置空白时的布局
        mLlEmpty = (RelativeLayout) mview.findViewById(R.id.ll_empty);
        mIvEmpty = (GifImageView) mview.findViewById(R.id.iv_zixun_zuixin_image_gif);
        mTvEmpty = (TextView) mview.findViewById(R.id.no_data_sms);
        tv_empty_click = (TextView) mview.findViewById(R.id.tv_empty_click);
        tvReloadError = (TextView) mview.findViewById(R.id.tv_reload_error);
        mIvErrorEmpty = (ImageView) mview.findViewById(R.id.iv_error_image);
        mIvSearchImage = (ImageView) mview.findViewById(R.id.iv_search_image);
        mRecyclerView.setEmptyView(mLlEmpty);
        //是否显示没有更多数据，和提示文字
        isShowNoMoreLayout = isShowNoMoreLayout();
        showMoreTips = setShowNoMoreTips();
        //
        initRefreshView();
//        settingStatusBar();
        initUI();
        return mview;
    }

    protected int setRefreshBg() {
        return R.color.color_f8f8f8;
    }


    protected void initUI() {
    }

    /**
     * 添加设置布局的的方法（修改布局可以重写该方法）
     *
     * @return
     */
    protected View setRefreshLayout() {
        return View.inflate(context, R.layout.activity_base_refresh, null);
    }

    /**
     * 强制显示空信息，用于adapter带有header等情况
     */
    public void forceShowEmptyInfo(boolean showEmpty, int deltaMargin) {
        if (showEmpty) {
            //先设置空数据信息
            showErrorInfo(errorMsg, false);
            View emptyView = getRecyclerView().getEmptyView();
            if (emptyView != null) {
                RelativeLayout rlTop = emptyView.findViewById(R.id.rl_top);
                RelativeLayout ll = (RelativeLayout) rlTop.getParent();
                if (ll != null) {
                    //设置top margin
                    RecyclerView.Adapter<? extends RecyclerView.ViewHolder> adapter1 = adapter;
                    int header = 0;
                    if (adapter1 instanceof HeaderAndFooterWrapperAdapter) {
                        header = ((HeaderAndFooterWrapperAdapter) adapter1).getHeadersCount();
                    }
                    int topMargin = 0;
                    for (int i = 0; i < header; i++) {
                        View view = getRecyclerView().getChildAt(i);
                        if (view != null) {
                            topMargin += view.getHeight();
                        }
                    }
                    if (ll.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
                        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) ll.getLayoutParams();
                        layoutParams.topMargin = topMargin + deltaMargin;
                        ll.setLayoutParams(layoutParams);
                    }
                }
                //将其设为显示
                emptyView.setVisibility(View.VISIBLE);
            }
        } else {
            if (getRecyclerView().getEmptyView() != null) {
                getRecyclerView().getEmptyView().setVisibility(View.GONE);
            }
        }
    }


    /**
     * 获取跟布局
     */
    public View getRootView() {
        return View.inflate(context, R.layout.activity_base_refresh, null);
    }

    protected void initRefreshView() {
        mRecyclerView.setLayoutManager(createLayoutManager(getActivity()));
        if (mData == null) {
            mData = new ArrayList<>();
        }
        //设置分隔线
        RecyclerView.ItemDecoration itemDecoration = createItemDecoration(getActivity());
        if (itemDecoration != null) {//判断是否为空，以便子类可以设置不加分割线
            mRecyclerView.addItemDecoration(itemDecoration);
        }
        adapter = createAdapter(mData);
        mRecyclerView.setAdapter(adapter);
        swipeToLoadLayout.setRefreshEnabled(isRefreshEnable());
        swipeToLoadLayout.setLoadMoreEnabled(isLoadMore());
        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);
        //如果是第一次进入，并且设置使用缓存
        if (isFirst && !TextUtils.isEmpty(getCacheKey())) {
            cacheKey = getCacheKey();
            List<T> cacheData = null;
            String listBeansStr = SpUtil.getStr(context, cacheKey, "");
            if (!StringUtils.isEmpty(listBeansStr)) {
                cacheData = (ArrayList) JSON.parseArray(listBeansStr, (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
                onRequestSuccess(cacheData, 0); //0 表示是缓存  1表示不是缓存
                isFirst = false;

            }
        }
        isSearch = requestFirstData();
        //点击灰色图片，加载动画，重新请求数据
        mIvErrorEmpty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showErrorInfo(null, true);
                getListData(firstPageNo);
            }
        });
        tvReloadError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showErrorInfo(null, true);
                getListData(firstPageNo);
            }
        });
        tv_empty_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mOnNoDataClickListener != null) {
                    mOnNoDataClickListener.noDataClick();
                }
            }
        });

        mIvSearchImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mIvSearchImage.setVisibility(View.GONE);
                mIvEmpty.setVisibility(View.VISIBLE);
                getListData(firstPageNo);
            }
        });
//        swipeToLoadLayout.setRefreshing(true);
        onFirstRefresh();
        //上拉加载更多没数据的布局
        if (isShowNoMoreLayout) {
            loadNoDataView = LayoutInflater.from(context).inflate(R.layout.layout_no_more_data, null);
            mTvNoMoreDataTip = loadNoDataView.findViewById(R.id.tv_load_more_no_data);
        }

    }

    /**
     * 是否需要首次加载数据，搜索页面使用
     */
    protected boolean requestFirstData() {
        //下面两行是第一次进去显示gif动画
        getListData(firstPageNo);
        //进来的时候首先加载动画
        showErrorInfo(null, true); // 他只表示 加载中，为空，请求失败显示哪一种方式 (不包含布局显示隐藏和显示)
        return false;
    }

    /**
     * 分割线
     *
     * @param context the context
     * @return 默认为 {@linkplain DividerItemDecoration}，用的是R.drawable.item_divider
     */
    protected RecyclerView.ItemDecoration createItemDecoration(Context context) {
//        return new DividerItemDecoration(context, DividerItemDecoration.VERTICAL_LIST, R.drawable.item_divider);
//        holder.recycler_view_search_item_data.addItemDecoration(new DividerItemDecoration(mContext,DividerItemDecoration.VERTICAL_LIST, R.drawable.item_divider_f5f5f5_1,false));
        return null;
    }

    protected void onRequestSuccess(List<T> data, int i) {
        if (mRecyclerView == null || data == null || mData == null) {
            return;
        }
        if (data.size() >= 0) {
            //如果是下拉刷新，则先清空数据，在加数据
            if (mPageNo <= firstPageNo) {
                mData.clear();
                //如果不是缓存，并且在第一页。则每次刷新保存一次
                if (i == 1) {
                    String str = JSON.toJSONString(data);
                    SpUtil.putStr(context, cacheKey, str);
                }
            }
            mData.addAll(data);
        }
        if (mData.size() == 0) {
            if (isSearch) { // 搜索页面无数据
                mIvEmpty.setVisibility(View.GONE);
                mIvSearchImage.setVisibility(View.VISIBLE);
            } else {
                showErrorInfo("暂时没有数据", false); //暂时没有数据
            }
        }
        if (mPageNo <= firstPageNo) {
            onRefreshComplete();
            //上拉刷新后去掉底部没有更多数据的footer
            if (isLoadMore() && showNoMoreData && isShowNoMoreLayout) {
                showNoMoreData = false;
                swipeToLoadLayout.setLoadMoreEnabled(true);
                mRecyclerView.removeFootView(loadNoDataView);
            }
        } else {
            onLoadMoreComplete();
            //底部没有更多数据的footer
            if (mData.size() > 0 && data.size() == 0 && isShowNoMoreLayout) {
                showNoMoreData = true;
                swipeToLoadLayout.setLoadMoreEnabled(false);
                if (!TextUtils.isEmpty(showMoreTips)) {
                    mTvNoMoreDataTip.setText(showMoreTips);
                }
                //
                mRecyclerView.addFootView(loadNoDataView);
            }
        }
    }

    /**
     * 是否显示没有更多数据的布局
     *
     * @return
     */
    protected boolean isShowNoMoreLayout() {
        return false;
    }

    /**
     * 没有更多数据的布局的提示文字
     *
     * @return
     */
    protected String setShowNoMoreTips() {
        return "";
    }

    @Override
    public void initData() {
    }

    @Override
    public void onRefresh() {
        mPageNo = firstPageNo;
        getListData(firstPageNo);
    }

    /**
     * 主动调用刷新，滚动到顶部，然后调用手动刷新
     */
    public void manualRefresh() {
        if (mRecyclerView != null) {
            mRecyclerView.scrollToPosition(0);
        }

        if (swipeToLoadLayout != null) {
            swipeToLoadLayout.manualRefresh();
        }
    }

    @Override
    public void onLoadMore() {
        mPageNo++;
        getListData(mPageNo);
    }


    protected void onRequestSuccess(List<T> data) {
        onRequestSuccess(data, 1);
    }

    /**
     * 加载失败时调用
     */
    protected void onRequestFail() {
        onRefreshComplete();
        showErrorInfo("网络请求失败", false);
    }

    protected void onRequestFail(String message) {
        onRefreshComplete();
        showErrorInfo(message, false);
    }

    /**
     * 加载失败时调用
     */
    protected void onRequestFail(Throwable e) {
        if (mPageNo == 1) {
            if (mData != null && mData.size() > 0) {
                onRefreshComplete();
            } else {
                if (e instanceof ApiException) {
                    ApiException result = (ApiException) e;
                    if (result.getCode() == 1002) {
                        onRequestFail("请检查网络");
                    } else {
                        onRequestFail();
                    }
                } else {
                    onRequestFail();
                }
            }

        } else {
            onLoadMoreComplete();
        }
    }

    /**
     * 未请求到数据时调用
     */
    protected void onRequestDataNull() {
        onRefreshComplete();
        showErrorInfo("暂时没有数据", false);
    }

    protected void onRequestDataNull(String message) {
        onRefreshComplete();
        showErrorInfo(message, false);
    }

    /**
     * 搜索页面没有请求到数据
     */
    protected void onRequestSearchDataNull() {
        onRefreshComplete();
        mIvEmpty.setVisibility(View.GONE);
        mIvSearchImage.setVisibility(View.VISIBLE);
    }

    /**
     * 刷新完成时调用
     */
    private void onRefreshComplete() {
        adapter.notifyDataSetChanged();
        swipeToLoadLayout.setRefreshing(false);
    }

    /**
     * 释放刷新
     */
    public void onRefreshRelase() {
        if (swipeToLoadLayout.isRefreshing()) {
            swipeToLoadLayout.setRefreshing(false);
        }
    }

    /**
     * 主动点击去刷新
     */
    public void onRefreshClick() {
        swipeToLoadLayout.setRefreshing(true);
    }

    /**
     * 第一次刷新
     */
    private void onFirstRefresh() {
        if (setFirstFlag()) {
            swipeToLoadLayout.setRefreshing(true);
        }
    }

    protected boolean setFirstFlag() {
        return isFirstFlag;
    }

    /**
     * 加载完成时，执行{@linkplain RecyclerView.Adapter#notifyDataSetChanged() 通知数据变化}
     * 和{@linkplain SwipeToLoadLayout2#setLoadingMore(boolean, boolean) 完成加载更多并保持位置}
     */
    protected void onLoadMoreComplete() {
        adapter.notifyDataSetChanged();
        swipeToLoadLayout.setLoadingMore(false, true);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    protected void showErrorInfo(String text, boolean isLoading) {
        if (TextUtils.isEmpty(errorMsg)) {
            //由于image相对于text定位，所以不要设为gone
            mTvEmpty.setVisibility(View.INVISIBLE);
        } else {
            mTvEmpty.setVisibility(View.VISIBLE);
            mTvEmpty.setText(errorMsg);
        }
        //如果正在加载
        if (isLoading) {
            mIvEmpty.setVisibility(View.VISIBLE);
            mIvErrorEmpty.setVisibility(View.GONE);
        } else {
            mIvEmpty.setVisibility(View.GONE);
            mIvErrorEmpty.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 设置页面
     *
     * @param pageNo
     */
    protected void setPageNo(int pageNo) {
        this.mPageNo = pageNo;
    }


    /**
     * 设置是否可以刷新（子类可以重写该方法）
     *
     * @return
     */
    protected boolean isRefreshEnable() {
        return true;
    }

    /**
     * 设置是否可以加载更多（子类可以重写该方法）
     *
     * @return
     */
    protected boolean isLoadMore() {
        return true;
    }

    public EmptySupportedRecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    private String errorMsg;

    //===================================================================================================================================================

    /**
     * 失败页面自己的文案
     *
     * @param data
     */
    protected void onRequestSuccess(List<T> data, String message, int imageResource) {
        mTvEmpty.setText(message);
        errorMsg = message;
        mIvErrorEmpty.setBackgroundResource(imageResource);
        if (data == null) {
            data = new ArrayList<>();
        }

        int i = 1;
        if (mRecyclerView == null || data == null || mData == null) {
            return;
        }
        if (data.size() >= 0) {
            //如果是下拉刷新，则先清空数据，在加数据
            if (mPageNo <= firstPageNo) {
                mData.clear();
                //如果不是缓存，并且在第一页。则每次刷新保存一次
                if (i == 1) {
                    String str = JSON.toJSONString(data);
                    SpUtil.putStr(context, cacheKey, str);
                }
            }
            mData.addAll(data);
        }

        if (mData.size() == 0) {
            if (TextUtils.isEmpty(message)) {
                //由于image相对于text定位，所以不要设为gone
                mTvEmpty.setVisibility(View.INVISIBLE);
            } else {
                mTvEmpty.setVisibility(View.VISIBLE);
                mTvEmpty.setText(message);
            }

            tvReloadError.setVisibility(View.GONE);
            mIvEmpty.setVisibility(View.GONE);
            mIvErrorEmpty.setVisibility(View.VISIBLE);
        }
        if (mPageNo <= firstPageNo) {
            onRefreshComplete();
            tvReloadError.setVisibility(View.GONE);
            mIvEmpty.setVisibility(View.GONE);
            mIvErrorEmpty.setVisibility(View.VISIBLE);

            //上拉刷新后去掉底部没有更多数据的footer
            if (isLoadMore() && showNoMoreData && isShowNoMoreLayout) {
                showNoMoreData = false;
                swipeToLoadLayout.setLoadMoreEnabled(true);
                mRecyclerView.removeFootView(loadNoDataView);
            }
        } else {
            onLoadMoreComplete();
            //底部没有更多数据的footer
            if (mData.size() > 0 && data.size() == 0 && isShowNoMoreLayout) {
                showNoMoreData = true;
                swipeToLoadLayout.setLoadMoreEnabled(false);
                if (!TextUtils.isEmpty(showMoreTips)) {
                    mTvNoMoreDataTip.setText(showMoreTips);
                }
                //
                mRecyclerView.addFootView(loadNoDataView);
            }
        }
    }

    /**
     * 失败页面自己的文案，最下面的点击事件回调
     *
     * @param data
     */
    protected void onRequestNoDataClickSuccess(List<T> data, String message, int imageResource, String btuMessage) {
        mTvEmpty.setText(message);
        errorMsg = message;
        mIvErrorEmpty.setBackgroundResource(imageResource);

        int i = 1;
        if (mRecyclerView == null || data == null || mData == null) {
            return;
        }
        if (data.size() >= 0) {
            //如果是下拉刷新，则先清空数据，在加数据
            if (mPageNo <= firstPageNo) {
                mData.clear();
                //如果不是缓存，并且在第一页。则每次刷新保存一次
                if (i == 1) {
                    String str = JSON.toJSONString(data);
                    SpUtil.putStr(context, cacheKey, str);
                }
            }
            mData.addAll(data);
        }

        if (mData.size() == 0) {
            if (TextUtils.isEmpty(message)) {
                //由于image相对于text定位，所以不要设为gone
                mTvEmpty.setVisibility(View.INVISIBLE);
            } else {
                mTvEmpty.setVisibility(View.VISIBLE);
                mTvEmpty.setText(message);
            }

            if (!TextUtils.isEmpty(btuMessage)) {
                tv_empty_click.setText(btuMessage);
                tv_empty_click.setVisibility(View.VISIBLE);
            } else {
                tv_empty_click.setVisibility(View.INVISIBLE);
            }
            tvReloadError.setVisibility(View.GONE);
            mIvEmpty.setVisibility(View.GONE);
            mIvErrorEmpty.setVisibility(View.VISIBLE);
        }
        if (mPageNo <= firstPageNo) {
            onRefreshComplete();
            tvReloadError.setVisibility(View.GONE);
            mIvEmpty.setVisibility(View.GONE);
            mIvErrorEmpty.setVisibility(View.VISIBLE);

            //上拉刷新后去掉底部没有更多数据的footer
            if (isLoadMore() && showNoMoreData && isShowNoMoreLayout) {
                showNoMoreData = false;
                swipeToLoadLayout.setLoadMoreEnabled(true);
                mRecyclerView.removeFootView(loadNoDataView);
            }
        } else {
            onLoadMoreComplete();
            //底部没有更多数据的footer
            if (mData.size() > 0 && data.size() == 0 && isShowNoMoreLayout) {
                showNoMoreData = true;
                swipeToLoadLayout.setLoadMoreEnabled(false);
                if (!TextUtils.isEmpty(showMoreTips)) {
                    mTvNoMoreDataTip.setText(showMoreTips);
                }
                //
                mRecyclerView.addFootView(loadNoDataView);
            }
        }
    }

    /**
     * 加载失败时调用
     */
    protected void onRequestFail(Throwable e, String message, int imageResource) {
        mTvEmpty.setText(message);
        mIvErrorEmpty.setBackgroundResource(imageResource);

        if (mPageNo == 1) {
            if (mData != null && mData.size() > 0) {
                onRefreshComplete();
            } else {
                if (e instanceof ApiException) {
                    ApiException result = (ApiException) e;
                    if (result.getCode() == 1002) {
                        onRequestFailError("网络不给力，请检查网络");
                    } else if (result.getCode() == 1001) {
                        onRequestFailError("没有数据了!");
                    } else {
                        onRequestFailError("内容加载失败，请检查网络");
                    }
                } else {
                    onRequestFailError("内容加载失败，请检查网络");
                }
            }

        } else {
            onLoadMoreComplete();
        }
    }

    protected void onRequestFailError(String message) {
        onRefreshComplete();
        mTvEmpty.setVisibility(View.VISIBLE);
        mTvEmpty.setText(message);

        tvReloadError.setVisibility(View.VISIBLE);
        mIvEmpty.setVisibility(View.GONE);
        mIvErrorEmpty.setVisibility(View.VISIBLE);
    }

    public OnNoDataClickListener mOnNoDataClickListener;

    public interface OnNoDataClickListener {
        void noDataClick();
    }

    public void setOnNoDataClickListener(OnNoDataClickListener mListener) {
        this.mOnNoDataClickListener = mListener;
    }

}
